package com.imooc.oa.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.Reader;
import java.util.function.Function;

public class MybatisUtils {
    // 利用 static(静态) 属于类不属于对象，且全局唯一
    private static SqlSessionFactory sqlSessionFactory = null;
    // 利用静态块在初始化类时实例化sqlSessionFactory
    static {
        Reader reader = null;
        try{
            //读取 mybatis-config.xml
            reader = Resources.getResourceAsReader("mybatis-config.xml");
            // 构建 SqlSessionFactory
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        }catch(Exception e){
            // 初始化错误时，通过抛出异常ExceptionInInitializerError通知调用
            throw new ExceptionInInitializerError(e);
        }
    }

    public static Object executeQuery(Function<SqlSession,Object> func){
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try{
            Object obj = func.apply(sqlSession);
            return obj;
        }finally {
            sqlSession.close();
        }
    }

    public static Object executeUpdate(Function<SqlSession,Object> func){
        // openSession传入false参数代表手动提交/回滚事务
        SqlSession sqlSession = sqlSessionFactory.openSession(false);
        try{
            Object obj = func.apply(sqlSession);
            sqlSession.commit();
            return obj;
        }catch(Exception e) {
            //对前面失败的写操作进行回滚
            sqlSession.rollback();
            throw e;
        }finally {
            sqlSession.close();
        }
    }
}
